<script lang="ts" setup>
import { useRoute, useRouter } from 'vue-router';
import { Modal, message } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import { cloneDeep } from 'lodash-es';
import ExcelJS from 'exceljs';
import { useUpload } from '../useUpload';

const loading = ref<boolean>(false);

const columns = ref<any[]>([]);
const sheetname = ref<any>();
const data = ref<any[]>([]);
const router = useRouter();
const header = ref<any[]>([]);
const flag = ref<boolean>(true);
const oldheader = ['generalFieldA', 'generalFieldB', 'generalFieldC', 'generalFieldD', 'generalFieldE', 'generalFieldF', 'generalFieldG', 'generalFieldH', 'generalFieldI', 'generalFieldJ', 'generalFieldK', 'generalFieldL', 'generalFieldM', 'generalFieldN', 'generalFieldO'];
// 获取数据
function mergeHeader(headerData: any[]) {
  const isSame = [];
  for (let i = 0; i < headerData.length; i++) {
    for (let j = 0; j < Object.keys(headerData[i]).length; j++) {
      isSame.push({
        id: headerData[i].id,
        index: i,
        key: oldheader[j],
        data: headerData[i][oldheader[j]],
        isSame: headerData[i][oldheader[j]],
      });
    }
  }
  // 删除行相同元素
  for (let i = 1; i < isSame.length; i++) {
    if (isSame[i].data === isSame[i - 1].data && isSame[i].index === isSame[i - 1].index) {
      isSame[i].isSame = '';
    }
  }
  // 删除列相同的元素
  const len = isSame[isSame.length - 1].index;
  const row: any = [];
  let count = isSame[0].index;
  let cData = [];
  for (let i = 0; i < isSame.length; i++) {
    if (isSame[i].index !== count) {
      row.push({
        index: count,
        data: cData,
      });
      count = isSame[i].index;
      cData = [];
    }
    cData.push(isSame[i]);
  }
  row.push({
    index: count,
    data: cData,
  });
  for (let i = 1; i < row.length; i++) {
    for (let j = 0; j < row[i].data.length; j++) {
      if (row[i].data[j].data === row[i - 1].data[j].data) {
        row[i].data[j].isSame = '';
      }
    }
  }
  const h = [];
  for (let i = 0; i < len + 1; i++) {
    const hdata: any = { id: row[i].data[0].id, isField: 'true' };
    for (let j = 0; j < row[i].data.length; j++) {
      hdata[row[i].data[j].key] = row[i].data[j].isSame;
    }
    h.push(hdata);
  }
  return h;
}
async function getquarterData() {
  loading.value = true;
  await getquarterListBysheetname(sheetname.value).then((res: any) => {
    data.value = res.data;
    if (data.value.length === 0) {
      flag.value = false;
    }
  });
  // 处理数据
  const bodyData: any[] = data.value.filter((item: any) => item.isField !== 'true');
  for (let i = 0; i < data.value.length; i++) {
    if (data.value[i].isField === 'true') {
      const headerdata = Object.keys(data.value[i])
        .filter(key => (key.startsWith('generalField') || key.startsWith('isField') || key.startsWith('id')) && data.value[i][key] !== '')
        .reduce((acc: any, key) => {
          acc[key] = data.value[i][key];
          return acc;
        }, {});
      header.value.push(headerdata);
    }
  }
  header.value = mergeHeader(header.value);
  data.value = header.value.concat(bodyData);
  loading.value = false;
}

function getColumns() {
  loading.value = true;
  const header1 = header.value[0];
  const hlength = Object.keys(header1).length;
  for (let i = 0; i < hlength - 4; i++) {
    columns.value.push({
      dataIndex: oldheader[i],
      align: 'center',
    });
  }
  columns.value.push({
    dataIndex: 'operation',
    align: 'center',
    width: 150,
    fixed: 'right',
  });
  loading.value = false;
}
const route = useRoute();
onMounted(async () => {
  sheetname.value = route.query.assessmentMethod;
  await getquarterData().then(() => {
    getColumns(); // 确保在数据获取后调用 getHeaderData
  });
});
// 编辑和删除方法
const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data.value.find(item => item.id === id));
}

async function save(id: number) {
  const index = data.value.findIndex(item => item.id === id);
  if (index !== -1) {
    const newData = { ...data.value[index], ...editableData[id] };
    data.value[index] = newData;
    await updatePublicSheetupdate(newData).then(() => {
      message.success('修改成功!');
      delete editableData[id];
    });
  }
}

async function deleteData(id: number) {
  await deletequarterPublicSheet(id).then(() => {
    message.success('删除成功!');
    getquarterData(); // 重新获取数据
  });
}
function cancel(id: number) {
  delete editableData[id];
}

function onDelete(id: number) {
  Modal.confirm({
    title: '确定要删除吗?',
    okText: '是的',
    okType: 'danger',
    cancelText: '取消',
    onOk() {
      deleteData(id);
    },
  });
}

// 返回
function back() {
  router.push('/assessment_indicators/quarter');
}

// 新建表
function newExcel() {
  router.push({ path: '/assessment_indicators/newexcelheader', query: { title: 'quarter', name: sheetname.value } });
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      // loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            // 上传到数据库
            await addQuarterSheet(formData).then(async () => {
              message.success('上传成功！');
              // 移除文件
              handleRemove(file);
              // 更新数据
              data.value = [];
              columns.value = [];
              await getquarterData().then(() => {
                getColumns(); // 确保在数据获取后调用 getHeaderData
              });
            })
              .catch(async () => {
                message.error('上传失败');
                // 重新更新数据，将原先显示在页面的数据撤回
                data.value = [];
                columns.value = [];
                await getquarterData().then(() => {
                  getColumns(); // 确保在数据获取后调用 getHeaderData
                });
              });
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 新增
function updateGeneralFields(data: any): any {
  const { isField, sheetName, isDelete } = data;
  const updatedFields: Partial<any> = {
    id: new Date(), generalFieldA: '', generalFieldB: '', generalFieldC: '', generalFieldD: '', generalFieldE: '', generalFieldF: '', generalFieldG: '', generalFieldH: '', generalFieldI: '', generalFieldJ: '', generalFieldK: '', generalFieldL: '', generalFieldM: '', generalFieldN: '', generalFieldO: '',
  };
  return {
    isField,
    sheetName,
    isDelete,
    ...updatedFields,
  };
}
function getExceptId<T extends { id: any }>(data: T): Omit<T, 'id'> {
  const { id, ...rest } = data;
  return rest;
}
async function add() {
  const correctData = data.value[data.value.length - 1];
  data.value.push(updateGeneralFields(correctData));
  await addQuarterPublicSheetcreate(getExceptId(updateGeneralFields(correctData)));
  data.value = [];
  columns.value = [];
  await getquarterData().then(() => {
    getColumns(); // 确保在数据获取后调用 getHeaderData
  });
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            {{ sheetname }}
          </div>
          <a-button v-if="!flag" type="link" @click="newExcel">
            新建表
          </a-button>
          <a-button v-if="flag" type="link" @click="add">
            添加考核项
          </a-button>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-upload
            v-auth="'e-index-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
            :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-auth="'e-index-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button type="primary" @click="back">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        v-if="flag" :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1024 }" class="q-table"
        :pagination="false" bordered :show-header="false"
      >
        <template #bodyCell="{ record, column, text }: { record: any, column: any, text: any }">
          <template v-if="column?.dataIndex?.startsWith('general') && record.isField === 'false'">
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ record[column?.dataIndex as string] }}
              </template>
            </div>
          </template>
          <div v-if="column && record.isField === 'false'">
            <template v-if="column.dataIndex === 'operation'">
              <div class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a-typography-link @click="save(record.id)">保存</a-typography-link>
                  <a @click="cancel(record.id)">取消</a>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                </span>
              </div>
            </template>
          </div>
          <template v-else-if="record.isField === 'true'">
            <div class="table-title">
              <p>{{ text }}</p>
            </div>
          </template>
        </template>
      </a-table>
      <div v-else>
        <a-empty />
      </div>
    </div>
  </pubpagemain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .q-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }

    .table-title {
      width: 100%;
      height: 100%;
      font-weight: bold;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
